package net.lcqf.websocket.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/4/15 16:48
 * // +----------------------------------------------------------------------
 */
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

    private final SslContext sslContext;

    public WebSocketServerInitializer(SslContext sslContext) {
        this.sslContext = sslContext;
    }

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {

        if (sslContext != null) { channel.pipeline().addLast(sslContext.newHandler(channel.alloc())); }

        channel.pipeline()
                // 解析HTTP请求头，支持协议升级
                .addLast(new HttpServerCodec())
                // 合并HTTP分片请求，避免处理不完整数据包
                .addLast(new HttpObjectAggregator(65536))
                // 开启心跳检测
                .addLast(new IdleStateHandler(15,0,0))
                .addLast(new WebSocketServerCompressionHandler())
                // WebSocket协议升级处理器
                .addLast(new WebSocketServerProtocolHandler(
                        "/",            // 访问路径
                        null,             // 子协议
                        true,             // 允许扩展
                        65536,   // 最大帧大小
                        false,            // 不处理Close帧
                        true,             // 发送压缩数据
                        10000L            // 强制关闭超时(ms)
                ))
                .addLast(new ProtobufDecoder())
                .addLast(new ProtobufEncoder())
                .addLast(new WebSocketServerHandler());
    }
}
